<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Inventory;

use App\Models\Inventory\AreaCn;
use App\Models\Inventory\Transfer;
use App\Models\Stocking\StockingSku;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;

class TransferAuditAjax {

    public function approval($idArr){
        try{
            $count = 0;
            $userId = Admin::user()->id;
            $res = Transfer::query()->whereIn('id',$idArr)->get();
            foreach($res as $re){
                DB::beginTransaction();
                $re->status = 2; //已通过
                $re->ouser_id = $userId;
                $flag1 = $re->save();
                if(!$flag1){
                    DB::rollBack();
                    continue;
                }

                //站点
                $areaCn = AreaCn::query()->firstOrNew(['area_id' => $re->iarea_id,'psku_id' => $re->psku_id]);
                $areaCn->instant += $re->transfer_num;
                $flag2 = $areaCn->save();
                if(!$flag2){
                    DB::rollBack();
                }else{
                    StockingSku::upCnInstant($re->iarea_id.'_'.$re->psku_id);
                    $count++;
                    DB::commit();
                }
            }
            return response()->json(['status' => true, 'message' => '成功通过'.$count.'条记录']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误']);
        }
    }

    public function reject($idArr){
        try{
            $count = 0;
            $userId = Admin::user()->id;
            $res = Transfer::query()->whereIn('id',$idArr)->get();
            foreach($res as $re){
                DB::beginTransaction();
                $re->status = 3; //已驳回
                $re->ouser_id = $userId;
                $flag1 = $re->save();
                if(!$flag1){
                    DB::rollBack();
                    continue;
                }

                //站点
                $areaCn = AreaCn::query()->firstOrNew(['area_id' => $re->oarea_id,'psku_id' => $re->psku_id]);
                $areaCn->instant += $re->transfer_num;
                $flag2 = $areaCn->save();
                if(!$flag2){
                    DB::rollBack();
                }else{
                    StockingSku::upCnInstant($re->oarea_id.'_'.$re->psku_id);
                    $count++;
                    DB::commit();
                }
            }
            return response()->json(['status' => true, 'message' => '成功驳回'.$count.'条记录']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误']);
        }
    }

}
